import { View, Text, Image, Picker, Input } from "@tarojs/components";
import Taro, { useLoad, useDidShow } from "@tarojs/taro";
import "./index.scss";
import { AtIcon, AtList, AtListItem,AtCheckbox } from "taro-ui";
import { useState,useEffect  } from "react";
import { request } from "@/utils/request";
import { getGlobalData } from "@/globalData";
const productId = getGlobalData('payProductId');
const appId = getGlobalData('appId');
let familyList = [] 
const productPrice = 400
const productExchangeRate = 100
export default function Payment() {
  
  
  const [selectedFamilyMemberIndex, setSelectedFamilyMemberIndex] = useState(0);
  const [areaList, setAreaList] = useState([["贵州省"], ["毕节市"]]);
  const [selectedAreaIndex, setSelectedAreaIndex] = useState<any>();
  const [hasSelectedArea, setHasSelectedArea] = useState(false);
  const [familyMemberNameList, setFamilyMemberNameList] = useState<any[]>([]);
  // 被选中的家庭成员
  const [selectedFamilyMember, setSelectedFamilyMember] = useState<any>({});
  

  const [isAgreeAgreement,setIsAgreeAgreement] = useState(false)
  // 当前用户积分值
  const [currentIntegral, setCurrentIntegral] = useState(0);
  // 使用积分
  const [useIntegral, setUseIntegral] = useState('');
  // 抵扣金额
  const [deductionAmount, setDeductionAmount] = useState(0);
  // 抵扣后金额
  const [afterDeductionAmount, setAfterDeductionAmount] = useState(400.00);
  // 是否可以提交
  const [canSubmit, setCanSubmit] = useState(false);
  // 缴费年份
  const [payYear, setPayYear] = useState('');
  // 缴费标准
  const [payStandard, setPayStandard] = useState('');

  // 判断是否可以提交
  useEffect(() => {
    judgeCanSubmit()
  },[selectedFamilyMember,hasSelectedArea,isAgreeAgreement])
  function judgeCanSubmit(){
    // console.log('judgeCanSubmit')
    if(selectedFamilyMember.name && selectedFamilyMember.idCard && hasSelectedArea && isAgreeAgreement){
      setCanSubmit(true)
    }else{
      setCanSubmit(false)
    }
  }
  function formatNumber(num){
    return Math.ceil(num * 100) / 100
  }
  // 用户积分值变化
  function useIntegralChange(value){
    // console.log("useIntegralChange value:",value)
    let productNeedIntegral = productPrice * productExchangeRate
    if(value < 0 || value >currentIntegral || value > productNeedIntegral){
      Taro.showToast({ title: "积分输入错误", icon: "none" });
      return
    }
    setUseIntegral(String(Number(value)));
    // 抵扣价格
    let deductionPrice = formatNumber(Number(value) / productExchangeRate)
    setDeductionAmount(deductionPrice)
    setAfterDeductionAmount(formatNumber(productPrice - deductionPrice))
  }
  // 跳转到代缴服务协议
  function jumpToAgreementDJ(){
    // 代缴服务协议
    // Taro.navigateTo({
    //   url: "/pages/pureTextAgreement/index"
    // })
    Taro.navigateTo({
      url: '/pages/agreeAgreement/index?articleIds=690,1204'
    })
  }
  function jumpToAgreementSQ(){
    // 跳转到授权服务协议
    // Taro.navigateTo({
    //   url: "/pages/pureTextAgreement/index"
    // })
    Taro.navigateTo({
      url: '/pages/agreeAgreement/index?articleIds=690,1204'
    })
  }

  function changeSelectedFamilyPersonName(name) {
    if (selectedFamilyMember.status === 1) {
      Taro.showToast({ title: "该用户已实名认证", icon: "none" });
      return;
    }

    setSelectedFamilyMember((perv) => {
      return {
        ...perv,
        name: name,
      };
    });
  }
  function changeSelectedFamilyPersonIdcard(idCard) {
    
    if (selectedFamilyMember.status === 1) {
      Taro.showToast({ title: "该用户已实名认证", icon: "none" });
      return;
    }
    setSelectedFamilyMember((perv) => {
      return {
        ...perv,
        idCard,
      };
    });
  }
  // 列变化
  function areaColumnChange(event) {
    console.log(
      "修改的列为",
      event.detail.column,
      "，值为",
      event.detail.value
    );
  }
  function areaPickerChange(event) {
    console.log("areaPickerChange :", event.detail.value);
    setSelectedAreaIndex(event.detail.value);
    setHasSelectedArea(true);
    setPayYear('2026年')
    setPayStandard('400元')
  }
  function familyPickerChange(event) {
    console.log("familyPickerChange :", event.detail.value);
    let index = event.detail.value;
    setSelectedFamilyMemberIndex(index);
    setSelectedFamilyMember(familyList[index]);
  }
  function getFamilyGroupList() {
    request({
      url: "/api/payment/order/queryFamilyPatient",
      data: {
        token: Taro.getStorageSync("token"),
      },
      success(data) {
        console.log('getFamilyGroupList data:',data)
        // 如果有idcard 就是已经实名认证过，否则就是没有实名认证
        data.forEach(item=>{
          item.status = item.idCard ? 1 : 0
        })
        // 家庭组
        familyList = data
        // console.log("MyFamilyGroup respDataList:", respDataList);
        // let nameList = data.map(item=>{
        //   return item.custPhone
        // })
        setFamilyMemberNameList(familyList);
      },
    });
  }
  function getFamilyPoints(){
    let user = Taro.getStorageSync("user");
    if(user && user.id){
      request({
        url: `/api/payment/order/homePage`,
        data: {
          token: Taro.getStorageSync("token"),
          userId: user.id,
        },
        method: 'POST',
        success: function(data){
          console.log('getFamilyPoints data:',data)
          // 家庭成员
          setCurrentIntegral(data.familyPoints)
        }
      })
    }
    
  }
  // 用户实名校验
  function validateUserCert() {
    return new Promise((resolve) => {
      request({
        url:
          '/api/userCertification?userId=' +
          selectedFamilyMember.userId +
          '&name=' +
          selectedFamilyMember.name +
          '&idcard=' +
          selectedFamilyMember.idCard,
        method: 'POST',

        success: (res) => {
          console.log('validateUserCert res；', res)
          resolve(true)
        },
        fail: (code, msg, failData) => {
          console.log('validateUserCert fail；', code, msg, failData)
          Taro.showModal({
            title: '提示',
            content:failData.respData || '实名认证失败，请重新输入',
            confirmText: '好的'
          })
          resolve(false)
        }
      })
    })
  }
  // 提交
  async function submitData(){
    // 提交
    if(!canSubmit){
      return 
    }
    if(!selectedFamilyMember.userId){
      Taro.showModal({
        title: "提示",
        content: "请选择参保人",
      });
      return 
    }
    // 如果用户没有实名认证过
    if(selectedFamilyMember.status !== 1){
      if(!selectedFamilyMember.name || !selectedFamilyMember.idCard){
        Taro.showModal({
          title: "提示",
          content: "请填写姓名和身份证号",
        });
        return 
      }
      let idCard = selectedFamilyMember.idCard
      if (!/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(idCard)) {
        Taro.showToast({
          title: '身份证号格式错误',
          icon: 'none'
        })
        return
      }
      let certRes = await validateUserCert()
      if (!certRes) {

        return
      }else {
        setSelectedFamilyMember(perv=>{
          return {
            ...perv,
            status:1
          }
        })
      }
    }
    // Taro.showLoading({
    //   title: '正在提交',
    //   mask: true
    // })
    // 获取当前用户
    let user = Taro.getStorageSync("user");
    // 提交预支付订单
    let openid = Taro.getStorageSync("openid");
    console.log('openid:',openid)
    request({
      url: '/api/payment/order/createPaymentOrder/jsapi/'+openid,
      method:'POST',
      data:{
        amountPay: afterDeductionAmount,
        pointPay:Number(useIntegral),
        provincesId:'520000',
        provincesName:'贵州省',
        cityId:'520500',
        cityName:'毕节市',
        createUserId:user.id,
        familyGroupId:selectedFamilyMember.familyGroupId,
        userId:selectedFamilyMember.userId,
        year:'2026'
      },
      success(data:any){
        console.log('data.paymentResponse:',data.paymentResponse)
        const payInfo = data.paymentResponse
        const orderId = data.id
        // 如果payInfo存在，则是积分不够需要调用微信支付，否则不用调微信支付
        if(payInfo){
          console.log('创建订单成功 payInfo:',payInfo)
          // 调微信支付
          let params = {
            appId: payInfo.appid,
            nonceStr: payInfo.nonceStr,
            package: 'prepay_id='+payInfo.prepayId, // 固定值，以微信支付文档为主
            timeStamp: payInfo.timestamp,
            paySign: payInfo.sign,
            signType: 'RSA' // 根据签名算法生成签名
          };
          // 调微信支付
          pay(params,orderId);
        }else{
          Taro.navigateTo({
            url: `/pages/paySuccess/index?orderId=${orderId}`,
          })
        }
      },
      fail(code,message,data){
        Taro.showModal({
          title: '提示',
          content: message || '创建订单失败，请稍后重试',
          showCancel:false,
          confirmText:'确定'
        })
      },
      complete(){
        console.log('complete')
        Taro.hideLoading()
      }
    })
  }
  // 获取订单状态
  // function getOrderDetail(orderId){

  // }
  function pay(params,orderId) {
    Taro.requestPayment({
      ...params,
      success: (win) => {
        console.log('success win:',win)
        Taro.showLoading({
          title: '支付确认中',
          mask: true
        });
        setTimeout(async () => {
          // 支付成功后，跳转到支付成功结果页
          Taro.hideLoading();
          Taro.navigateTo({
            url: `/pages/paySuccess/index?orderId=${orderId}`,
          })
        }, 1500);
      },
      fail: (err) => {
        console.log('支付失败', err);
        Taro.reLaunch({
          url: `/pages/payOrderList/index?orderId=${orderId}`,
        })
        // Taro.showModal({
        //   title: '支付错误,请重试',
        //   showCancel: false,
        //   confirmText: '确定',
        //   success: (res) => {
            
        //   }
        // });
      }
    });
  }
  
  useDidShow(() => {
    console.log("Page loaded.");
    // 获取当前用户的家庭积分
    getFamilyPoints();
    
    // 是否同意
    let agree = Taro.getStorageSync("pages/agreeAgreement/index/agreeInsuranceAgreement")
    setIsAgreeAgreement(agree|| false)
    
  });
  useLoad(() => {
    console.log("Page loaded.");
    // 获取家庭列表
    getFamilyGroupList();
  });

  return (
    <View className="payment">
      <View className="form-wrap">
        <View className="banner">
          <Image
            className="img"
            src="https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-jifen/images/index2/banner-dj.png"
            mode="widthFix"
          ></Image>
        </View>

        <View className="form-box">
          <View className="title">参保人</View>

          <View className="form-input-item">
            <Picker
              className="picker"
              mode="selector"
              range={familyMemberNameList}
              range-key="custPhone"
              onChange={familyPickerChange}
              value={selectedFamilyMemberIndex}
            >
              <View className="form-input-item-inner">
                <View className="label">选择参保人：</View>
                {selectedFamilyMember.custPhone && (
                  <View className="value">
                    <Text className="value-txt">
                      {selectedFamilyMember.custPhone}
                    </Text>
                    <AtIcon
                      className="arrow"
                      value="chevron-right"
                      size="10"
                      color="#111"
                    ></AtIcon>
                  </View>
                )}
                {!selectedFamilyMember.custPhone && (
                  <View className="value">
                    <Text className="placeholder">请选择</Text>
                    <AtIcon
                      className="arrow"
                      value="chevron-right"
                      size="10"
                      color="#ccc"
                    ></AtIcon>
                  </View>
                )}
              </View>
            </Picker>
          </View>

          <View className="form-input-item">
            <View className="label">姓名：</View>
            <View className="value">
              <Input
                className="input"
                type="text"
                placeholder="请输入姓名"
                value={selectedFamilyMember.name}
                onInput={(event) => {
                  changeSelectedFamilyPersonName(event.detail.value);
                }}
                disabled={selectedFamilyMember.status === 1}
                placeholderClass="placeholder"
              />
            </View>
          </View>
          <View className="form-input-item">
            <View className="label">身份证：</View>
            <View className="value">
              <Input
                className="input"
                type="text"
                placeholder="请输入身份证号码"
                value={selectedFamilyMember.idCard}
                onInput={(event) => {
                  changeSelectedFamilyPersonIdcard(event.detail.value);
                }}
                disabled={selectedFamilyMember.status === 1}
                placeholderClass="placeholder"
              />
            </View>
          </View>
        </View>

        <View className="form-box">
          <View className="title">参保信息</View>

          <View className="form-input-item">
            <Picker
              className="picker"
              mode="multiSelector"
              range={areaList}
              onChange={areaPickerChange}
              value={selectedAreaIndex}
              onColumnChange={areaColumnChange}
            >
              <View className="form-input-item-inner">
                <View className="label">选择参保地区：</View>
                {
                  !hasSelectedArea && (
                    <View className="value">
                      <Text className="placeholder">请选择</Text>
                      <AtIcon className="arrow" value="chevron-right" size="10" color="#ccc"></AtIcon>
                    </View>
                  )
                }
                {
                  hasSelectedArea && 
                  (
                    <View className="value">
                      <Text className="value-txt">
                        { areaList[0][selectedAreaIndex[0]] }
                        { areaList[1][selectedAreaIndex[1]]}
                      </Text>
                      <AtIcon className="arrow" value="chevron-right" size="10" color="#111"></AtIcon>
                    </View>
                  )
                }
                

              </View>
            </Picker>
          </View>

          <View className="form-input-item">
            <View className="label">缴费年份：</View>
            <View className="value">{payYear}</View>
          </View>
          <View className="form-input-item">
            <View className="label">城乡居民缴费标准：</View>
            <View className="value">{payStandard}</View>
          </View>
        </View>

        <View className="time-des">
       
          <View className='icon'>!</View>
          <View className='text'>
            本服务面向毕节市城乡居民医保代缴为2025年9月23日至2026年2月28日，超期无法提供代缴服务
          </View>
        </View>

        <View className="form-box">
          <View className="title">
            <View className="title-left">积分抵扣</View>
            <View className="title-right">全家积分：{currentIntegral}</View>
          </View>

          <View className="form-input-item">
            <View className="label">使用积分：</View>
            <View className="value">
              <Input
                className="input"
                type="number"
                placeholder="请输入使用积分值"
                value={useIntegral}
                onInput={(event) => {
                  useIntegralChange(event.detail.value);
                }}
                placeholderClass="placeholder"
              />
            </View>
          </View>

          <View className="form-input-item">
            <View className="label">抵扣额：</View>
            <View className="value">{deductionAmount}元</View>
          </View>
        </View>
      </View>
      {/* 常见问题解答 */}
      <View className="qa">
        <View className="title">常见问题解答</View>
        <View className="qa-wrap">
          <View className="qa-item">
            <View className="question">国家城乡居民医保有什么好处？</View>
            <View className="answer">
              国家医保是最基础，最普惠的福利。无论是大病还是小病，都能有效抵御疾病带来的经济风险。为每个人的健康生活兜底，是必不可少的"健康保护伞"！
            </View>
          </View>

          <View className="qa-item">
            <View className="question">万户健康医保代缴服务靠谱吗？</View>
            <View className="answer">
              本服务是由政府权威指导，医保系统深度对接，全程操作安全透明，缴费安全有保证，让您省心无忧。
            </View>
          </View>

          <View className="qa-item">
            <View className="question">使用本服务有什么特别的福利吗？</View>
            <View className="answer">
              当然！使用万户健康医保代缴服务，可用万户积分宝直接抵扣部分缴费金额，轻松减轻经济负担，实惠看得见！抵扣规则清晰透明，在缴费页面可直接显示抵扣金额，只要积分余额充足就可以直接使用，无复杂附加条件。快来体验便捷又实惠的服务吧！
            </View>
          </View>

          
        </View>
      </View>
      {/* 同意协议 */}
      <View className="agreement">
        <AtIcon
            className="raido"
            value="check-circle"
            size="10"
            color={isAgreeAgreement ? "#F00" : "#999"}
            onClick={() => setIsAgreeAgreement(!isAgreeAgreement)}
          
          ></AtIcon>
        <View className="text">
          我已阅读并同意
          <Text className="link" onClick={jumpToAgreementDJ}>《万户健康居民医疗保险代缴服务协议》</Text>
          和<Text className="link" onClick={jumpToAgreementSQ}>《授权委托书》</Text>
        </View>
      </View>

      <View className="pay-footer">
        <View className="total">
          <View className="txt">抵扣后交费金额</View>
          <View className="money">￥<Text className='money-num'>{afterDeductionAmount}</Text></View>
        </View>
        <View className={['btn',canSubmit ? '' : 'disabled'].join(' ')} onClick={ submitData }>立即缴费</View>
      </View>
    </View>
  );
}
